package com.jiepos.mpos.biz.code.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.common.constant.DBConstant.Table;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.MenuButtonDao;
import com.jiepos.mpos.common.dao.MenuDao;
import com.jiepos.mpos.common.entity.App_Menu_CdEntity;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.IDFactoryUtil;
import com.jiepos.mpos.core.util.StringUtils;


/**
 * 
 * <p>标题: —— 菜单业务服务类</p>
 * <p>模块: 通用平台</p>
 * <p>版权: Copyright (c) 2017 江苏杰博实信息技术有限公司
 * @author 娄伟峰
 * @version 1.0
 * @since 2017年4月13日 上午9:08:29
 * @history（历次修订内容、修订人、修订时间等）
 */
@Service
public class MenuCodeService extends BaseService {
	
	@Autowired
	private MenuDao menuDao;
	@Autowired
	private MenuButtonDao menuButtonDao;

	/**
	 * 查询菜单列表json分页数据
	 * @param pagination 分页对象
	 * @param request
	 * @param menuEntity 菜单实体对象
	 * @param menuPname 上级菜单名称
	 * @return
	 */
	public Map getMenuPageList(Pagination pagination, HttpServletRequest request, App_Menu_CdEntity menuEntity,String menuPname) {
		StringBuffer sb = getInitSql("t1").append(",");
		sb.append("t1.menu_uuid as uuid, t1.menu_name,t1.menu_url,t1.menu_url1,t1.menu_url2,t2.menu_name as menuPname,t1.menu_orders");
		sb.append(" from ");
		sb.append(Table.T_APP_MENU_CD  );
		sb.append(" t1 left join ");
		sb.append(Table.T_APP_MENU_CD );
		sb.append(" t2 on t1.sup_menu_uuid=t2.menu_uuid where 1=1 ");
		List list = new ArrayList();
		if (!StringUtils.isBlank(menuEntity.getMenu_name())) {
			sb.append( " and t1.menu_name like ? " );
			list.add("%" + menuEntity.getMenu_name() + "%");
		}
		if (!StringUtils.isBlank(menuEntity.getMenu_url())) {
			sb.append( " and t1.menu_url like ? " );
			list.add("%" + menuEntity.getMenu_url() + "%");
		}
		if (!StringUtils.isBlank(menuPname)) {
			sb.append( " and t2.menu_name like ? " );
			list.add("%" + menuPname + "%");
		}
		pagination.queryString = sb.toString();
		pagination = this.getOrderSql(pagination, "t1");
		return menuDao.getPaginationMap(pagination, "t1", list);
	}
	
	/**
	 * 菜单树形结果,折叠
	 * @return
	 */
	public List<Map<String, Object>> getMenuTree(){
		return getMenuTree(false);
	}
	
	/**
	 * 菜单树形结果
	 * @param isOpen 是否打开，true打开，反之折叠
	 * @return
	 */
	public List<Map<String, Object>> getMenuTree(boolean isOpen){
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT menu_uuid mid, menu_url, sup_menu_uuid pid, menu_name mname")
		.append(" FROM ")
		.append(Table.T_APP_MENU_CD)
		.append(" where rec_st != '0' ")
		.append(" ORDER BY TO_NUMBER(MENU_ORDERS) DESC");
		List<Map<String, Object>> menus = menuDao.queryForList(sql.toString(), null);
		if(menus != null && !menus.isEmpty()){
			for(Map<String, Object> map : menus){
				map.put("open", isOpen);
			}
		}
		return menus;
	}

	/**
	 * 保存菜单信息
	 * @param menuEntity 菜单实体
	 * @param map 登录用户信息map
	 */
	public void saveMenu(App_Menu_CdEntity menuEntity,Map map) {	
		menuEntity.setRec_upd_usr_id(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_USER)));
		if (!StringUtils.isBlank(menuEntity.getMenu_uuid())) {
			App_Menu_CdEntity newMenuEntity = menuDao.findByParam("menu_uuid", menuEntity.getMenu_uuid());
 			menuEntity.setRec_upd_ts(new Timestamp(System.currentTimeMillis()));
			menuEntity.setRec_id(newMenuEntity.getRec_id());
			menuEntity.setRec_crt_ts(newMenuEntity.getRec_crt_ts());
			menuEntity.setLast_oper_in(SystemConstant.OPER_UPDATE);
			List noChangeList = new ArrayList();
			noChangeList.add("menu_uuid");
			menuDao.update(menuEntity,noChangeList);
		} else {
			menuEntity.setRec_crt_ts(new Timestamp(System.currentTimeMillis()));
			menuEntity.setRec_upd_ts(new Timestamp(System.currentTimeMillis()));
			menuEntity.setMenu_uuid(IDFactoryUtil.getUUID());
			menuEntity.setRec_st(SystemConstant.NORMAL_STATUS);
			menuEntity.setLast_oper_in(SystemConstant.OPER_ADD);
			menuDao.save(menuEntity);
		}
	}
	
	/**
	 * 根据记录id查询菜单信息实体对象
	 * @param menu_uuid 菜单uuid
	 */
	public App_Menu_CdEntity getMenuById(String menu_uuid) {
		if (StringUtils.isBlank(menu_uuid) || menu_uuid.equals("undefined")) {
			return new App_Menu_CdEntity();
		}
		return menuDao.findByParam("menu_uuid", menu_uuid);
	}
	
	/**
	 * 根据记录id集合删除数据
	 * @param menu_uuids 菜单uuid集合，中间以逗号分隔
	 */
	public void deleteMenuByIds(String menu_uuids) {
		menuDao.deleteByStatus("menu_uuid", menu_uuids);
		menuButtonDao.deleteByStatus("menu_uuid", menu_uuids);
	}
	
	/**
	 * 根据角色编码查询菜单集合
	 * @param roleUuid 角色编码
	 * @return
	 */
	public List<Map<String, Object>> getMenuTreeByRoleUuid(HttpServletRequest request){
		String roleUuid = String.valueOf(request.getSession().getAttribute(SystemConstant.SESSION_ROLE_UUID));
		if(StringUtils.isBlank(roleUuid)){
			return new ArrayList<>();
		}
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT MENU_UUID AS \"id\", MENU_NAME AS \"name\", MENU_URL AS \"url\", SUP_MENU_UUID AS \"pid\"")
		.append("  FROM (SELECT DISTINCT MC.MENU_UUID,")
		.append("                        MC.MENU_NAME,")
		.append("                        MC.SUP_MENU_UUID,")
		.append("                        MC.MENU_URL,")
		.append("                        TO_NUMBER(MC.MENU_ORDERS) MENU_ORDERS")
		.append("          FROM ").append(Table.T_APP_MENU_CD).append(" MC")
		.append("         WHERE MC.").append(SystemConstant.REC_ST).append(" = '").append(SystemConstant.NORMAL_STATUS).append("'")
		.append("         START WITH MC.MENU_UUID IN")
		.append("                    (SELECT T.MENU_UUID")
		.append("                       FROM ").append(Table.T_APP_MENUAUTH_INF).append(" T")
		.append("                      WHERE T.ROLE_UUID = ?")
		.append("                        AND T.").append(SystemConstant.REC_ST).append(" = '").append(SystemConstant.NORMAL_STATUS).append("')")
		.append("        CONNECT BY PRIOR MC.SUP_MENU_UUID = MC.MENU_UUID)")
		.append(" ORDER BY MENU_ORDERS DESC");
		List<String> param = new ArrayList<>();
		param.add(roleUuid);
		List<Map<String, Object>> menus = menuDao.queryForList(sql.toString(), param);
		if(menus != null && !menus.isEmpty()){
			for(Map<String, Object> map : menus){
				map.put("open", true);
			}
		}
		return menus;
	}

}
